package com.ruoyi.flow.service.impl;

import com.ruoyi.core.entity.UserContext;
import com.ruoyi.flow.entity.Constant;
import com.ruoyi.flow.entity.machine.Handler;
import com.ruoyi.flow.service.FlowUserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//@ConditionalOnMissingBean(FlowUserService.class)
public class InnerDefaultFlowUserServiceImpl implements FlowUserService {

    @Override
    public UserContext currentUser() {
        UserContext userContext = new UserContext();
        userContext.setUserId("-");
        userContext.setUserName("-");
        userContext.setUserType("1");
        userContext.setDeptId("-");
        userContext.setDeptName("-");
        return userContext;
    }

    @Override
    public boolean checkUser(List<Handler> handlers) {
        if (isAdmin()) {
            return true;
        }
        if (handlers != null && handlers.size() > 0) {
            UserContext userContext = currentUser();
            for (Handler handler : handlers) {
                if (Constant.HandlerType.USER.equals(handler.getType())) {
                    if (handler.getId().equals(userContext.getUserId()) || handler.getId().equals(userContext.getUserName())) {
                        return true;//有权限
                    }
                }
                if (Constant.HandlerType.ROLE.equals(handler.getType())) {
                    if (userContext.getRoles() != null && userContext.getRoles().size() > 0) {
                        if (userContext.getRoles().stream().anyMatch(x -> handler.getId().equals(x.getRoleId()) || handler.getId().equals(x.getRoleCode()))) {
                            return true;//有权限
                        }
                    }
                }
                if (Constant.HandlerType.DEPT.equals(handler.getType())) {
                    if (handler.getId().equals(userContext.getDeptId()) || handler.getId().equals(userContext.getDeptCode())) {
                        return true;//有权限
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean isAdmin() {
        UserContext userContext = currentUser();
        return "1".equals(userContext.getUserType());
    }
}
